//
//  HWHomeBannerCell.swift
//  HWanGame
//
//  Created by 王昌健 on 2021/12/24.
//  Copyright © 2021 94Wan. All rights reserved.
//

import UIKit
import FSPagerView
import JXPageControl

class HWHomeBannerCell: UITableViewCell {
    var banner: FSPagerView!
    var collectionView:UICollectionView!
    let collectionProtocol = HWHomeBannerProtocol()
    lazy var codePageControl: JXPageControlJump = {
        let pageControl = JXPageControlJump(frame: CGRect(x: 0, y: 0,width: UIScreen.main.bounds.width,height: 30))
        pageControl.numberOfPages = 0
        pageControl.activeColor = .colorWithHexString(hexString: "#FEAC0A")
        pageControl.inactiveColor = .colorWithHexString(hexString: "#C2C2C2")
        pageControl.activeSize = CGSize(width: 22*widthScale, height: 4*widthScale)
        pageControl.inactiveSize = CGSize(width: 10*widthScale, height: 4*widthScale)
        pageControl.columnSpacing = 3*widthScale
        
        return pageControl
    }()
    var model:HWHomeModel? {
        didSet {
            
            if (model?.slide?.count ?? 0) > 0 {
                banner.snp.updateConstraints { make in
                    make.height.equalTo(424*widthScale)
                }
            } else {
                banner.snp.updateConstraints { make in
                    make.height.equalTo(0)
                }
            }
            self.banner.reloadData()
            collectionProtocol.model = model
            self.collectionView.reloadData()
            if (collectionProtocol.model?.gongneng?.count ?? 0) % 5 == 0{
                codePageControl.numberOfPages = (collectionProtocol.model?.gongneng?.count ?? 0) / 5
            }else {
                codePageControl.numberOfPages = ((collectionProtocol.model?.gongneng?.count ?? 0) / 5) + 1
            }
            print(codePageControl.numberOfPages)
            let numberOfPages = CGFloat(codePageControl.numberOfPages)
            banner.snp.updateConstraints { make in
                make.bottom.equalTo(-65.0*widthScale*numberOfPages - 9*widthScale*(numberOfPages - 1)  - 9*widthScale)
            }
            
            collectionView.snp.updateConstraints { make in
                make.height.equalTo(65.0*widthScale*numberOfPages + 9*widthScale*(numberOfPages - 1))
            }
            
        }
    }
    
    var didClickBanner:((_ :String)->())?
    var didClickItem:((_:HWHomeGongNengModel)->())?
    class func cellWithTableView(tableView:UITableView) -> (HWHomeBannerCell) {
        let reUse:String = "HWHomeBannerCell"
        
        var cell = tableView.dequeueReusableCell(withIdentifier: reUse)
        
        if cell == nil {
            cell = HWHomeBannerCell.init(style: UITableViewCell.CellStyle.default, reuseIdentifier: reUse)
        }
        
        return cell as! HWHomeBannerCell
    }
    
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        initUI()
        
        initFrame()
        
        addAction()
    }
    
    func initUI() -> Void {
        selectionStyle = UITableViewCell.SelectionStyle.none
        backgroundColor = UIColor.white
        
        banner = FSPagerView()
        banner.dataSource = self
        banner.delegate = self
        banner.isInfinite = true
        banner.register(HWPagerCell.self, forCellWithReuseIdentifier: "HWPagerCell")
        banner.automaticSlidingInterval = 3
        banner.interitemSpacing = 9*widthScale
        banner.itemSize = CGSize(width: 350*widthScale, height: 424*widthScale)
        banner.removesInfiniteLoopForSingleItem = true
        
        contentView.addSubview(banner)
        
        //        bottomView = UIView()
        //        bottomView.backgroundColor = .colorWithHexString(hexString: "#F7F7F7")
        //        contentView.addSubview(bottomView)
        
        let flowL = UICollectionViewFlowLayout.init()
        flowL.scrollDirection = .vertical
        collectionView = UICollectionView.init(frame: .zero, collectionViewLayout: flowL)
        collectionView.delegate = collectionProtocol
        collectionView.dataSource = collectionProtocol
        collectionView.isPagingEnabled = true
        collectionView.backgroundColor = .white
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.register(HWHomeBannerItemCell.self, forCellWithReuseIdentifier: "HWHomeBannerItemCell")
        contentView.addSubview(collectionView)
        
        contentView.addSubview(codePageControl)
        
        codePageControl.isHidden = true
        
    }
    
    func initFrame() -> Void {
        banner.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview().priority(.low)
            make.height.equalTo(424*widthScale)
            make.bottom.equalTo(-170*widthScale)
        }
        
        //        bottomView.snp.makeConstraints { make in
        //            make.left.right.equalTo(banner)
        //            make.top.equalTo(banner.snp.bottom)
        //            make.bottom.equalToSuperview()
        //        }
        
        collectionView.snp.makeConstraints { make in
            make.left.right.equalTo(0)
            make.top.equalTo(banner.snp.bottom).offset(9*widthScale)
            make.height.equalTo(65*widthScale)
        }
        
        codePageControl.snp.makeConstraints { make in
            make.left.right.equalTo(0)
            make.top.equalTo(collectionView.snp.bottom).offset(5*widthScale)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }
    
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        
        // Configure the view for the selected state
    }
    
}
extension HWHomeBannerCell {
    func addAction() -> Void {
        self.collectionProtocol.scrollDidScroll = {
            scrollView in
            let progress = scrollView.contentOffset.x / scrollView.bounds.width
            //            let currentPage = Int(round(progress))
            //            self.codePageControl.currentPage = currentPage
            self.codePageControl.progress = progress
        }
        
        self.collectionProtocol.didClickItem = {
            self.didClickItem?($0)
        }
    }
}
extension HWHomeBannerCell:FSPagerViewDelegate,FSPagerViewDataSource {
    func numberOfItems(in pagerView: FSPagerView) -> Int {
        return self.model?.slide?.count ?? 0
    }
    
    func pagerView(_ pagerView: FSPagerView, cellForItemAt index: Int) -> FSPagerViewCell {
        
        let cell = pagerView.dequeueReusableCell(withReuseIdentifier: "HWPagerCell", at: index) as! HWPagerCell
        cell.model = self.model?.slide?[index]
        return cell
    }
    
    func pagerView(_ pagerView: FSPagerView, didSelectItemAt index: Int) {
        self.didClickBanner?(model?.slide?[index].gid ?? "")
    }
    
    
}

class HWPagerCell:FSPagerViewCell {
    var bgView:UIView!
    var gameImageView:UIImageView!
    var alphaView:UIView!
    var nameLabel:UILabel!
    var starImageView:UIImageView!
    var scoreLabel:UILabel!
    var typeLabel:UILabel!
    var rightLabel:UILabel!
    var textTagCollectionView:TTGTextTagCollectionView!
    
    var model:HWHomeSlideModel? {
        didSet {
            gameImageView.sd_setImage(with: URL(string: model?.image ?? ""), completed: nil)
            nameLabel.text = model?.game_name
            scoreLabel.text = model?.point
            typeLabel.text = model?.type
            rightLabel.text = "详情"
            textTagCollectionView.removeAllTags()
            for (idx,txt) in (model?.biaoqian ?? []).enumerated() {
                let content = TTGTextTagStringContent.init(text: txt)
                content.textFont = UIFont.systemFont(ofSize: 9*widthScale)
                let normalStyle = TTGTextTagStyle.init()
                normalStyle.cornerRadius = 7*widthScale
                normalStyle.extraSpace = CGSize.init(width: 8*widthScale, height: 2*widthScale)
                normalStyle.borderColor = .clear
                normalStyle.backgroundColor = .colorWithAlphaHexString(hexString: "#FFFFFF", alpha: 0.22)
                normalStyle.shadowColor = .clear
                if idx == 0 {
                    content.textColor = UIColor.colorWithHexString(hexString: "#FF726A")
                }else if idx == 1 {
                    content.textColor = UIColor.colorWithHexString(hexString: "#1CD67E")
                }else if idx == 2 {
                    content.textColor = UIColor.colorWithHexString(hexString: "#F5B75B")
                }else if idx == 3 {
                    content.textColor = UIColor.colorWithHexString(hexString: "#444444")
                }else{
                    content.textColor = UIColor.colorWithHexString(hexString: "#CEA224")
                }
                
                let tag = TTGTextTag.init()
                tag.content = content
                tag.style = normalStyle
                textTagCollectionView.addTag(tag)
            }
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        initUI()
        
        initFrame()
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func initUI() -> Void {
        
        contentView.layer.shadowColor = UIColor.clear.cgColor
        
        gameImageView = UIImageView()
        gameImageView.layer.cornerRadius = 18*widthScale
        gameImageView.layer.masksToBounds = true
        gameImageView.backgroundColor = .clear
        gameImageView.contentMode = .scaleAspectFill
        addSubview(gameImageView)
        
        alphaView = UIView()
        alphaView.frame = CGRect(x: 0, y: 0, width: 350*widthScale, height: 112*widthScale)
        gameImageView.addSubview(alphaView)
        UIColor.gradientColor(view: alphaView, colors: [UIColor.colorWithAlphaHexString(hexString: "#333333", alpha: 0).cgColor,
                                                        UIColor.colorWithAlphaHexString(hexString: "#000000", alpha: 1).cgColor,],start: CGPoint(x: 0, y: 0),end: CGPoint(x: 0, y: 1))
        
        nameLabel = HWLabel.createBoldLabel(title: "", color: "#FFFFFF", font: 16*widthScale)
        nameLabel.numberOfLines = 1
        gameImageView.addSubview(nameLabel)
        
        starImageView = UIImageView()
        starImageView.image = UIImage(named: "homeYellowStar")
        gameImageView.addSubview(starImageView)
        
        scoreLabel = HWLabel.createBoldLabel(title: "", color: "#F2C36E", font: 11*widthScale)
        gameImageView.addSubview(scoreLabel)
        
        typeLabel = HWLabel.createBoldLabel(title: "", color: "#888888", font: 11*widthScale)
        gameImageView.addSubview(typeLabel)
        
        rightLabel = HWLabel.createBoldLabel(title: "", color: "#FA8C08", font: 14*widthScale)
        rightLabel.layer.cornerRadius = 14*widthScale
        rightLabel.layer.borderWidth = 1*widthScale
        rightLabel.layer.borderColor = UIColor.colorWithHexString(hexString: "#FA8C08").cgColor
        rightLabel.textAlignment = .center
        gameImageView.addSubview(rightLabel)
        
        textTagCollectionView = TTGTextTagCollectionView.init(frame: .zero)
        textTagCollectionView.delegate = self;
        textTagCollectionView.alignment = TTGTagCollectionAlignment.left;
        textTagCollectionView.manualCalculateHeight = true;
        gameImageView.addSubview(textTagCollectionView)
    }
    
    private func initFrame() -> Void {
        
        gameImageView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(424*widthScale)
        }
        
        alphaView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(112*widthScale)
        }
        
        
        nameLabel.snp.makeConstraints { make in
            make.left.equalTo(13*widthScale)
            make.top.equalTo(346*widthScale)
            make.height.equalTo(20*widthScale)
            make.right.lessThanOrEqualTo(rightLabel.snp.left)
        }
        
        starImageView.snp.makeConstraints { make in
            make.width.height.equalTo(11*widthScale)
            make.left.equalTo(nameLabel)
            make.top.equalTo(nameLabel.snp.bottom).offset(8*widthScale)
        }
        
        scoreLabel.snp.makeConstraints { make in
            make.left.equalTo(starImageView.snp.right).offset(2*widthScale)
            make.centerY.equalTo(starImageView)
        }
        
        typeLabel.snp.makeConstraints { make in
            make.left.equalTo(scoreLabel.snp.right).offset(4*widthScale)
            make.centerY.equalTo(scoreLabel)
        }
        
        
        rightLabel.snp.makeConstraints { make in
            make.right.equalTo(-13*widthScale)
            make.height.equalTo(28*widthScale)
            make.centerY.equalTo(typeLabel)
            make.width.equalTo(62*widthScale)
        }
        
        textTagCollectionView.snp.makeConstraints { make in
            make.left.equalTo(nameLabel)
            make.right.equalTo(0)
            make.top.equalTo(starImageView.snp.bottom).offset(8*widthScale)
        }
    }
    
}

extension HWPagerCell:TTGTextTagCollectionViewDelegate{
    @nonobjc func textTagCollectionView(_ textTagCollectionView: TTGTextTagCollectionView!, didTap tag: TTGTextTag!, at index: UInt) {
        
        
    }
}
